import {Component, OnDestroy, OnInit, ViewChild} from '@angular/core';
import {Events, NavController} from '@ionic/angular';
import {ConfigService} from '../../services/config.service';
import {HttpService} from '../../services/http.service';
import {Observable} from 'rxjs';
import {UrlAndOPT} from '../../common/url-and-opt.enum';
import {AppConfig} from '../../common/app-config.enum';
import * as networkReducer from '../../reducers/network.reducer';
import {select, Store} from '@ngrx/store';

@Component({
  selector: 'app-lend',
  templateUrl: './lend.page.html',
  styleUrls: ['./lend.page.scss'],
})
export class LendPage implements OnInit, OnDestroy {

  @ViewChild('infiniteScroll') infiniteScroll;
  public dataList: any[] = [];
  // 筛选条件
  public condition: any = {
    currPage: 1, // 当前页码
    pageSize: 20, // 每页数据条数
    bidType: 0, // 分类条件(默认全部)
    title: '' // 筛选关键字
  };
  timerMap: any = {};

  constructor(
    private navCtrl: NavController,
    private events: Events,
    private configService: ConfigService,
    private service$: HttpService,
    private store: Store<networkReducer.NetworkState>
  ) {
    // 侦听网络状态变化
    this.store.pipe(select(networkReducer.getNetwork))
      .subscribe(networkState => {
        if (networkState.status  === 1) {
          this.getDataList()
            .subscribe(obj => {
              this.handler(obj);
            });
        }
      });
    // 手势解锁后重新加载数据(防止进入手势解锁页时就TAB中的页面，解锁成功后数据不刷新)
    this.events.subscribe(AppConfig.TOPIC_TAB_REFRESH, () => {
      this.getDataList()
        .subscribe(obj => {
          this.handler(obj);
        });
    });
  }

  ngOnInit() {
  }

  ngOnDestroy(): void {
    this.events.unsubscribe(AppConfig.TOPIC_TAB_REFRESH);
  }

  // 获取列表数据
  private getDataList(): Observable<any> {
    return this.service$.doRequest(UrlAndOPT.lend_bidList, this.condition);
  }

  private handler(obj) {
    if (obj) {
      const records = obj.records;
      this.condition = {...this.condition, currPage: records['currPage'], pageSize: records['pageSize']};
      this.dataList = records['page'];
      // 计时侦听
      this.setTimerMap(obj);
      // 根据列表长度判断是否禁用加载
      this.infiniteScroll.disabled = this.dataList.length === records['totalCount'];
    } else {
      this.infiniteScroll.disabled = true;
    }
  }

  // 设置预发布状态计时侦听
  setTimerMap(obj) {
    const nowTime = obj['nowTime']['time'];
    this.timerMap = this.dataList.reduce((previousValue, currentValue) => {
      if (currentValue['preDate']['time'] > nowTime) { // 预发布时间晚于当前时间
        previousValue[currentValue['bidIdSign']] = {
          bidCountDown: currentValue['preDate']['time'] - nowTime,
          interval: setInterval(() => {
            if (this.timerMap[currentValue['bidIdSign']]['bidCountDown'] < 1000) {
              this.timerMap[currentValue['bidIdSign']]['bidCountDown'] = 0;
              clearInterval(this.timerMap[currentValue['bidIdSign']]['interval']);
            } else {
              this.timerMap[currentValue['bidIdSign']]['bidCountDown'] -= 1000;
            }
          }, 1000)
        };
      }
      return previousValue;
    }, {});
  }

  // 下拉刷新列表或多条件过滤数据
  doRefresh(event?) {
    this.condition.currPage = 1;
    this.getDataList()
      .subscribe(obj => {
        this.handler(obj);
        if (event) {  // 如果为下拉刷新，关闭下拉组件
          event.target.complete();
        }
      }, () => {
        if (event) {
          event.target.complete();
        }
      });
  }

  // 上拉加载更多
  loadMoreData(event) {
    this.condition.currPage++;
    this.getDataList()
      .subscribe(obj => {
        if (obj) {
          const records = obj.records;
          // 累加数据
          this.dataList = [...this.dataList, ...records['page']];
          // 计时侦听
          this.setTimerMap(obj);
          // 根据列表长度判断是否禁用加载
          this.infiniteScroll.disabled = this.dataList.length === records['totalCount'];
        }
        // 关闭上拉组件
        event.target.complete();
      });
  }

  // 查看标的详情
  pushDetail(bidIdSign: any) {
    this.navCtrl.navigateForward(['/bid', {bidIdSign: bidIdSign, from: '/tabs/lend'}]);
  }

}
